<template>
  <page-wrap
    back
    hide-tab
    title="报告列表"
    stay-still
    bgColor="linear-gradient(179deg, #f8e5c9 0%, #fffbf5 100%)"
  >
    <view class="report-container">
      <view class="report-item">
        <view class="header">
          <view class="line"></view>
          <view class="title">职途报告</view>
          <view
            class="create"
            v-if="careerReportSrc"
            @click="handleCreateReport"
            >{{ isProducing ? "刷新" : "重新生成" }}</view
          >
        </view>
        <view class="content">
          <image class="img" :src="careerReport"></image>
          <view class="name-box">
            <view class="name">职途报告</view>
            <view class="time">{{ updateTime }}生成</view>
          </view>
          <view class="check-text" v-if="careerReportSrc" @click="previewReport"
            >查看报告</view
          >
          <view class="check-text" v-else @click="handleCreateReport"
            >生成报告</view
          >
        </view>
      </view>
      <view class="report-item">
        <view class="header">
          <view class="line"></view>
          <view class="title">推荐职业分析报告</view>
        </view>
        <view
          class="content"
          v-for="(item, index) in recommendReportList"
          :key="index"
        >
          <image class="img" :src="careerReport"></image>
          <view class="name-box">
            <view class="name">{{ item.activityName }}</view>
            <view class="time"
              >{{ item.createdTime || "2023-11-10 15:09:11" }}上传</view
            >
          </view>
          <view class="check-text" @click="previewRecommendReport(item)"
            >查看报告</view
          >
        </view>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import CryptoJS from "crypto-js";
import {
  recommendReport,
  createZTReport,
  getUserRightsList,
} from "@/api/modules/career";
export default {
  data() {
    return {
      careerReport: this.$imgBase + "career/careerReport.png",
      recommendReportList: [],
      careerReportSrc: "",
      updateTime: "",
      cardType: "",
      isProducing: false,
    };
  },
  computed: {
    formattedDate: function () {
      const today = new Date(); //获取当前时间
      const month = (today.getMonth() + 1).toString().padStart(2, "0"); //获取月份，不足两位的前面补0
      const year = today.getFullYear().toString().substr(0); //获取年份的后两位
      const day = today.getDate().toString().padStart(2, "0"); //获取天数，不足两位的前面补0
      return `${year}-${month}-${day}`; //拼接成mm-yy-dd的格式
    },
  },
  onLoad(opt) {
    this.careerReportSrc = decodeURIComponent(opt.careerReportSrc);
    this.updateTime = opt.updateTime || this.getNowFormatDate();
    this.cardType = opt.cardType || "1";
  },
  onShow() {
    this.isProducing = false;
  },
  created() {},
  mounted() {
    this.recommendReportFn();
  },
  methods: {
    getUserRightsListFn() {
      // 这个uid一定要传，因为在interceptors中，没有传参的请求的请求头不会带上uid，而这个请求一定要uid
      getUserRightsList({ uid: "" }).then((res) => {
        if (res.code == 200) {
          const temp = res.data.find((item) => item.rightId == "7");
          if (temp) {
            this.careerReportSrc = temp.extra.pdfUrl || temp.extra.wordUrl;
            if (temp.updateTime != this.updateTime) {
              this.isProducing = false;
              uni.showToast({ icon: "none", title: "职途报告生成成功", duration: 1000 });
              this.updateTime = temp.updateTime;
            } else {
              uni.showToast({
                icon: "none",
                title: "职途报告还在生成中，请稍后再次点击刷新！",
                duration: 1000
              });
            }
          }
        }
      });
    },
    handleCreateReport() {
      if (this.isProducing) {
        this.getUserRightsListFn();
        return;
      }
      this.isProducing = true;
      uni.showToast({
        icon: "none",
        title: "职途报告生成中,请需要等待30秒左右喔~",
        duration: 3000,
      });
      const params = {
        cardType: this.cardType,
      };
      createZTReport(params).then((res) => {
        if (res.code == 200) {
          this.careerReportSrc = res.data;
          this.updateTime = this.getNowFormatDate();
          uni.showToast({ icon: "none", title: "职途报告生成成功" });
        }
      });
    },
    recommendReportFn() {
      recommendReport({ uid: "" }).then((res) => {
        if (res.code == 200) {
          this.recommendReportList = Array.isArray(res.data) ? res.data : [];
        }
      });
    },
    previewRecommendReport(item) {
      if (!item.activityTypeCode) {
        uni.showToast({ icon: "none", title: "缺少activityIdCode" });
      }
      let url =
        "/pagesSub/companyCenter/case/detail?id=" +
        item.activityIdCode +
        "&&isFromZhishenji=" +
        1 +
        "&&isGetCollect=" +
        1 +
        "&&showType=report";

      url +=
        "&&sourceFrom=" + this.encrypt("zhishenji" + this.formattedDate, "");

      uni.navigateTo({
        url,
      });
    },
    encrypt(word, keyStr) {
      // word, keyStr第一个参数是加密的字段名字  第二个是key值（16位）
      keyStr = keyStr || "*%&^%$&*()347845"; // 密文（密钥）
      var key = CryptoJS.enc.Utf8.parse(keyStr);
      var srcs = CryptoJS.enc.Utf8.parse(word);
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });
      return encrypted.toString();
    },
    previewReport() {
      uni.showLoading({
        title: "正在打开报告",
      });
      uni.downloadFile({
        url: this.careerReportSrc,
        success: (res) => {
          if (+res.statusCode === 200) {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: function (saveRes) {
                setTimeout(() => {
                  uni.hideLoading();
                  uni.openDocument({
                    filePath: saveRes.savedFilePath,
                  });
                }, 1500);
              },
            });
          }
        },
      });
    },
    getNowFormatDate() {
      const date = new Date(); //获取当前时间
      let month = date.getMonth() + 1; //月份处理
      let day = date.getDate();
      month = month < 10 ? "0" + month : month; //月份为1-9月,在其前面加0
      day = day < 10 ? "0" + day : day; //日期为1-9号,在其前面加了0
      const s1 = "-"; //定义年月日分隔符-
      const s2 = ":"; //定义时分秒分隔符:
      //拼接年月日,时分秒
      const currDate =
        date.getFullYear() +
        s1 +
        month +
        s1 +
        day +
        " " +
        date.getHours() +
        s2 +
        date.getMinutes() +
        s2 +
        date.getSeconds();
      return currDate;
    },
  },
};
</script>
<style lang="scss" scoped>
.report-container {
  padding: 16rpx;
  .report-item {
    &:not(:first-child) {
      margin-top: 16rpx;
    }
    padding: 36rpx 16rpx 16rpx 16rpx;
    background-color: #fff;
    .header {
      display: flex;
      align-items: center;
      margin-bottom: 36rpx;
      .line {
        margin-right: 20rpx;
        width: 6rpx;
        height: 28rpx;
        background: #f75a3e;
        border-radius: 3rpx;
      }
      .title {
        font-size: 32rpx;
        font-family: PingFang-SC-Heavy, PingFang-SC;
        font-weight: 600;
        color: #222222;
      }
      .create {
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #555555;
        border-radius: 8rpx;
        border: 2rpx solid #bfbfbf;
        margin-left: auto;
        padding: 8rpx 20rpx;
      }
    }
    .content {
      padding: 24rpx;
      background-color: #fef6ef;
      display: flex;
      align-items: center;
      &:not(:last-child) {
        margin-bottom: 20rpx;
      }
      .img {
        width: 68rpx;
        height: 68rpx;
        margin-right: 24rpx;
        flex-shrink: 0;
      }
      .name-box {
        max-width: 60%;
        .name {
          font-size: 32rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          color: #222222;
          white-space: nowrap;
          overflow-x: hidden;
          text-overflow: ellipsis;
        }
        .time {
          font-size: 24rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          color: #bfa0a0;
          margin-top: 12rpx;
        }
      }
      .check-text {
        flex-shrink: 0;
        margin-left: auto;
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        color: #f75a3e;
      }
    }
  }
  .tips {
    padding: 16rpx;
    color: #888;
  }
}
</style>
